<script setup lang="ts">
import { Locale as VantLocale } from "vant";
import API from "@/api";
import { useWindowSize, useScrollBottom } from "@/hooks";
import userinfo from "@/store/userinfo";
import { messages, countryCodeOptions } from "@/const/lang";

const piniaUserinfo: any = userinfo();
const title = useTitle();

const {t, locale } = useI18n();

// 公用监听
useWindowSize();
useScrollBottom();
const queryLangList = () => {
  API.langList({}).then((res) => {
    if (res.code === 200) {
      piniaUserinfo.setLangList(res.data);
      let defalutLang = res.data.find((item:any) => item?.defLanguage === 1);
      if(!piniaUserinfo.getLang?.languageCode && defalutLang) {
        piniaUserinfo.setActiveLang(defalutLang);
      }
    }
  })
}
queryLangList()
watch(
  () => piniaUserinfo.getHaslogged,
  (val) => {
    if (val) {
      piniaUserinfo.queryUserMoney();
    }
  },
  {
    immediate: true,
  }
);

// 网站名称描述ico等配置
piniaUserinfo.queryWebConfig();
watch(
  () => piniaUserinfo.getWebConfig,
  (val) => {
    if (val) {
      let favicon: any = document.querySelector('link[rel="icon"]');
      if (favicon) {
        favicon.href = val?.urlLogo;
      } else {
        favicon = document.createElement("link");
        favicon.rel = "icon";
        favicon.href = val?.urlLogo;
        document.head.appendChild(favicon);
      }

      title.value = val?.urlTitle;

      let metaDom = <HTMLMetaElement>(
        document.querySelector('meta[name="description"]')
      );
      if (!metaDom) {
        metaDom = document.createElement("meta");
        metaDom.name = "description";
        metaDom.content = val?.urlExplain;
        document.getElementsByTagName("head")[0].appendChild(metaDom);
      } else {
        metaDom.setAttribute("content", val?.urlExplain);
      }
    }
  },
  {
    flush: "post",
  }
);

// 多语言修改
watch(
  () => locale.value,
  () => {
    if (
      locale.value &&
      (messages as any)[locale.value]?.lang?.vant
    ) {
      VantLocale.use(locale.value, (messages as any)[locale.value]?.lang?.vant);
    }
  },
  {
    immediate: true,
  }
);
watch(() => piniaUserinfo.getLang, (val) => {
  if(val?.languageCode) {
    nextTick(() => {
      locale.value = val?.languageCode;
    })
  }
}, {
  immediate: true,
})

</script>

<template>
  <!-- <van-nav-bar safe-area-inset-top /> -->
  <RouterView />
  <van-number-keyboard safe-area-inset-bottom />
</template>

<style lang="scss" scoped></style>
